# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(pROC)
library(egg)
library(randomForest)
library(Boruta)
library(magrittr)
library(e1071)
library(optparse)
library(tidyverse)
library(extrafont)
library(showtext)
showtext_auto()

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--cc", default = "../calculate_config.txt", type = "character", help = "config file"),
  make_option("--pc", default = "../rfPlot_plot_config.txt", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))
font_import(paths = c("/usr/share/fonts/myFonts"), recursive = F, prompt = F)

options(digits = 3)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/parse_config.R"))
fontFamily <- configGet(plotConfigData, "fontFamily")
baseFamily <- fontFamily

baseFamily

parent <- paste0("./")
createWhenNoExist(parent)

fileName <- list.files("./", full.names = T) %>%
  keep(~str_detect(.x, "_VarImp.csv"))

if (!file.exists(fileName)) {
  quit(status = 0)
}

configData <- read_tsv(opt$cc, col_names = F) %>%
  set_colnames(c("arg", "value"))

topM <- configGet(configData, "topM") %>%
  as.numeric()

plotData <- read_csv(fileName) %>%
  slice(1:topM) %>%
  mutate(Var = fct_reorder(Var, VarImp, .desc = F))

plotData

p <- ggplot(plotData, mapping = aes(x = VarImp, y = Var)) +
  ylab("") +
  xlab("VarImp") +
  theme_bw(base_size = 8.8, base_family = baseFamily) +
  theme(axis.text.x = element_text(size = 10, hjust = 1, vjust = 1,family = baseFamily), legend.position = 'top',
        legend.text = element_text(size = 9), legend.title = element_text(size = 11),
        axis.text.y = element_text(size = 6, family = baseFamily),
        axis.title.y = element_text(size = 11,family = baseFamily), axis.title.x = element_text(size = 12), panel.grid.major.x = element_blank(),
        panel.border = element_rect(size = 0.75), panel.grid.minor.x = element_blank(), panel.grid.major.y = element_line(
      linetype = 2, color = "#BEBEBE")
  ) +
  geom_point(fill = "blue", shape = 21, color = "blue", size = 2)

pdfFileName <- paste0(parent, "/LR_Imp.pdf")
rowNum <- nrow(plotData)
defaultHeight <- max(2 + (rowNum - 10) * 0.15, 2) + 2
finalHeight <- getFinalHeight(height, defaultHeight, opt$pc)
p <- getBasicPlotArg(p)

ggsave(limitsize = FALSE, pdfFileName, p, width = width, height = finalHeight)






